package modules.warn.controller;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import luxing.common.controller.BaseController;
import luxing.common.service.SmsService;
import luxing.constant.SmsConfig;
import luxing.exception.BusinessException;
import luxing.hibernate.CriteriaQuery;
import luxing.util.CriteriaQueryUtil;
import luxing.util.DateUtil;
import luxing.util.JsonUtil;
import luxing.util.LoginUserUtil;
import luxing.web.model.DataGrid;
import luxing.web.model.Result;
import manage.tenant.entity.Tenant;
import manage.tenant.service.TenantService;
import modules.loan.entity.Loan;
import modules.loan.service.LoanService;
import modules.sys.entity.Log;
import modules.sys.service.LogService;

/**
 * 
 * @author zzc
 *
 */
@Controller
@RequestMapping("/loanWarnController")
public class LoanWarnController extends BaseController {

	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(LoanWarnController.class);

	@Autowired
	private LogService logService;
	@Autowired
	private LoanService LoanService;
	@Autowired
	private TenantService tenantService;
	@Autowired
	private SmsService smsService;

	/**
	 * 列表页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "index")
	public ModelAndView index(HttpServletRequest request) {
		return new ModelAndView("modules/warn/loanWarn-list");
	}

	/**
	 * 列表数据
	 * 
	 * @param loan
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "list")
	public void list(Loan loan, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		try {
			CriteriaQuery cq = new CriteriaQuery(Loan.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, loan, request.getParameterMap());
			// 提醒类型
			String warnDateType = request.getParameter("warnDateType");
			String endDateBegin = request.getParameter("endDate_begin");
			String endDateEnd = request.getParameter("endDate_end");
			if (StringUtils.isNotBlank(endDateBegin) || StringUtils.isNotBlank(endDateEnd)
					|| (warnDateType != null && warnDateType.equals("2"))) {
				// 按时间范围
				if (StringUtils.isNotBlank(endDateBegin)) {
					cq.ge("endDate", DateUtil.strToDate(endDateBegin, "yyyy-MM-dd"));
				}
				if (StringUtils.isNotBlank(endDateEnd)) {
					cq.le("endDate", DateUtil.strToDate(endDateEnd, "yyyy-MM-dd"));
				}
			} else if ((warnDateType == null || warnDateType.equals("1"))
					&& (StringUtils.isBlank(endDateBegin) && StringUtils.isBlank(endDateEnd))) {
				// 下月到期
				Calendar calBegin = Calendar.getInstance();
				calBegin.add(Calendar.YEAR, -100);
				cq.ge("endDate", calBegin.getTime());
				Calendar calEnd = Calendar.getInstance();
				calEnd.add(Calendar.MONTH, 2);
				calEnd.set(Calendar.DATE, 0);
				cq.le("endDate", calEnd.getTime());
			}
			cq.add();
			LoanService.listByPage(cq, true);
			listView(response, dataGrid);
		} catch (Exception e) {
			logger.error("还款到期查询失败", e);
			throw new BusinessException("还款到期查询失败", e);
		}
	}

	/**
	 * 发送短信页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goSendSms")
	public ModelAndView goSendSms(Loan loan, HttpServletRequest req) {
		if (StringUtils.isNotBlank(loan.getId())) {
			loan = LoanService.get(Loan.class, loan.getId());
			req.setAttribute("loanPage", loan);
		}
		return new ModelAndView("modules/warn/loanWarn-sms");
	}

	/**
	 * 发送短信
	 * 
	 * @param vehicleWarn
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doSendSms")
	@ResponseBody
	public Result doSendSms(Loan loan, HttpServletRequest request) {
		String msg = null;
		String phone = request.getParameter("ownerPhone");
		try {
			Tenant tenant = tenantService.get(Tenant.class, LoginUserUtil.getLoginUser().getTenantId());
			// 判断用户余额
			if (tenant.getBalance().compareTo(Tenant.BALANCE_MIN) < 0) {
				msg = "账户余额不足,发送失败.";
				return Result.error(msg);
			}
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("period", loan.getPeriod().toString());
			paramMap.put("warnTypeName", "借款");
			paramMap.put("endDate", DateUtil.dateToStr(loan.getEndDate(), "yyyy-MM-dd"));
			String templateParam = JsonUtil.toJson(paramMap);
			smsService.sendSms(phone, SmsConfig.template_owner_warn, templateParam, tenant);
			msg = "号码\"" + phone + "\"短信发送成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_SMS);
		} catch (Exception e) {
			msg = "号码\"" + phone + "\"短信发送失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

}
